package io.github.shang11925.shangweb2.day240904;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.*;

@WebServlet("/login")
public class MyHttpServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println("username = " + username);
        System.out.println("password = " + password);
        //连接数据库 homework
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("JDBC驱动加载成功！");

            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/homework", "root", "zzh211925");
            statement = connection.createStatement();
            resultSet = statement.executeQuery("select * from user ");
            boolean flag = false;
            while (resultSet.next()) {
                if (resultSet.getString("username").equals(username) && resultSet.getString("password").equals(password)) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                resp.getWriter().println("<h1>登录成功</h1>");
            }
            else {
                resp.getWriter().println("<1>登录失败</h1>");
            }
            System.out.println("flag = " + flag);
        } catch (SQLException e) {
            e.printStackTrace(); // 打印错误信息
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (resultSet != null) resultSet.close();
                if (statement != null) statement.close();
                if (connection != null) connection.close();
            } catch (SQLException e) {
                e.printStackTrace(); // 关闭连接时的异常处理
            }
        }
    }
}
